<template>
  <div class="search-container">
    <div v-if="advSearchStyle!=='dragpanel'" class="dialog-container">
      <div v-if="searchConditions.length>0" class="search-condition-bar">
        <label>高级搜索<i class="el-icon-arrow-right" /></label>
        <div class="scroll-pane-container">
          <scroll-pane ref="scrollPane" class="scroll-pane-wrapper">
            <span v-for="(item,key) in searchConditions" :key="key">{{ item.label+"："+item.value }} <i class="el-icon-close" @click.prevent.stop="clearSearchCondition(item)" /></span>
          </scroll-pane>
        </div>
        <div class="clear-condition-btn">
          <el-button size="mini" type="text" @click.prevent.stop="clearSearchCondition()">清除搜索</el-button>
        </div>
      </div>

      <el-dialog v-if="dialogFormVisible" v-el-drag-dialog :visible.sync="dialogFormVisible" :close-on-click-modal="false" width="800px" title="高级搜索">
        <el-form :model="advSearchMap">
          <el-form-item v-for="(column,key) in searchColumns" :key="key" :label="column.title" :label-width="formLabelWidth">
            <el-select v-if="column.listAdvSearchElement==='select'" v-model="advSearchMap[column.field]" :placeholder="'请选择'+column.title" :clearable="true" @change="$forceUpdate()">
              <el-option v-for="(value,text,optKey) in column.formatterMap" :key="optKey" :label="value" :value="text" />
            </el-select>
            <el-radio-group v-else-if="column.listAdvSearchElement==='radio'" v-model="advSearchMap[column.field]" :placeholder="'请选择'+column.title" @change="$forceUpdate()">
              <el-radio v-for="(value,text,optKey) in column.formatterMap" :key="optKey" :label="text">{{ value }}</el-radio>
            </el-radio-group>
            <div v-else-if="column.listAdvSearchElement==='date'" class="block">
              <el-date-picker
                v-model="advSearchMap[column.field+'_START']"
                class="date_time_inner"
                :format="column.propFormatter?column.propFormatter.replace('format：',''):'yyyy-MM-dd HH:mm:ss'"
                :type="column.datePickerType"
                placeholder="选择开始时间"
                :value-format="column.propFormatter?column.propFormatter.replace('format：',''):'yyyy-MM-dd HH:mm:ss'"
              />
              至
              <el-date-picker
                v-model="advSearchMap[column.field+'_END']"
                class="date_time_inner"
                :format="column.propFormatter?column.propFormatter.replace('format：',''):'yyyy-MM-dd HH:mm:ss'"
                :type="column.datePickerType"
                placeholder="选择结束时间"
                :value-format="column.propFormatter?column.propFormatter.replace('format：',''):'yyyy-MM-dd HH:mm:ss'"
              />
            </div>
            <el-input v-else v-model="advSearchMap[column.field]" autocomplete="off" @input="$forceUpdate()" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button plain @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click.native="handleAdvSearch">确 定</el-button>
        </div>
      </el-dialog>
    </div>
    <div v-if="advSearchStyle==='dragpanel'&&dialogFormVisible" class="dragpanel-container">
      <dynamic-form :table-field-info="searchFormFieldInfo" :vo="advSearchMap" :can-edit="canEdit" form-width="100%" />
      <div class="panel-footer">
        <el-button icon="el-icon-search" type="primary" @click.native="handleAdvSearch">开始搜索</el-button>
        <el-button icon="el-icon-close" plain class="custom_plain_default_btn" @click.native="clearSearchCondition()">清除搜索</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import variables from '@/wapp/common/styles/variables.scss'
import { sortByKey } from '@/global/utils/index'
const moment = require('moment')

export default {
    name: 'Search',
    components: {

    },
    props: {
        moduleInfo: { type: Object, default: function() { return {} } }, // 模块映射配置信息，包含api接口地址等信息
        tbColumns: { type: Array, default: function() { return [] } }
    },
    data() {
        return {
            dialogFormVisible: false,
            advSearchMap: {},
            formLabelWidth: variables.formLabelWidth,
            searchConditions: [],
            searchFormFieldInfo: [],
            advSearchStyle: 'dialog'
        }
    },
    computed: {
        searchColumns() {
            let copyTbColumns = JSON.parse(JSON.stringify(this.tbColumns))
            copyTbColumns = copyTbColumns.filter(item => {
                if (item.searchable && item.field !== 'index') {
                    if (item.listAdvSearchElement === 'date') {
                        if (item.propFormatter === '' && item.elementFormatter !== '') {
                            item.propFormatter = item.elementFormatter
                        }
                        if (item.propFormatter === undefined || item.propFormatter === '' || item.propFormatter === null) item.propFormatter = 'format：yyyy-MM-dd HH:mm:ss'

                        if (item.propFormatter && item.propFormatter.indexOf(' HH:mm') !== -1) {
                            item.datePickerType = 'datetime'
                        } else {
                            item.datePickerType = 'date'
                        }
                    }
                    return true
                }
            })
            copyTbColumns = sortByKey(copyTbColumns, 'listAdvSearchIndex', 'asc')
            return copyTbColumns
        }
    },
    watch: {
        dialogFormVisible(val) {
            const searchInput = document.querySelector('.navbar-search .el-input__inner')
            if (val || this.searchConditions.length > 0) {
                if (searchInput !== null) searchInput.disabled = true
                this.$bus.emit('unfloadAdvSearch', true)
            } else {
                if (searchInput !== null) searchInput.disabled = false
                this.$bus.emit('unfloadAdvSearch', false)
            }
        },
        searchConditions(val) {
            const searchInput = document.querySelector('.navbar-search .el-input__inner')
            if (this.dialogFormVisible || val.length > 0) {
                if (searchInput !== null) searchInput.disabled = true
                this.$bus.emit('unfloadAdvSearch', true)
            } else {
                if (searchInput !== null) searchInput.disabled = false
                this.$bus.emit('unfloadAdvSearch', false)
            }
        }
    },
    created() {
        // advSearchStyle：高级搜索样式，默认为弹层窗口
        if (window.advSearchStyle) {
            this.advSearchStyle = window.advSearchStyle
        }
        if (this.advSearchStyle === 'dragpanel' && this.moduleInfo.listAdvSearchExpandPanel === 1) {
            this.handleSearch(null, 'and')
        }

        this.$bus.on('searchListData', this.handleSearch)
        this.$bus.on('setAdvSearchMap', this.setAdvSearchMap)
    },
    beforeDestroy() {
        this.$bus.off('searchListData', this.handleSearch)
        this.$bus.off('setAdvSearchMap', this.setAdvSearchMap)
    },
    methods: {
        setAdvSearchMap(advSearchMap) {
            this.advSearchMap = advSearchMap
            this.$forceUpdate()
        },
        handleSearch(searchText, searchAndOr, mode) {
            if (mode !== undefined && mode !== this.$parent.mode) {
                return
            }

            this.resetDateSearchField()

            if (searchAndOr === 'or') {
                this.advSearchMap = {}
                this.searchConditions = []

                this.$parent.searchAndOr = searchAndOr
                this.$parent.searchMap = {}
                if (searchText.trim() !== '') {
                    const _this = this
                    this.searchColumns.forEach(function(item) {
                        let formatterVal = ''
                        if (item.formatterMap) {
                            for (const key in item.formatterMap) {
                                if (item.formatterMap[key] === searchText) {
                                    formatterVal = key
                                }
                            }
                        }
                        if (formatterVal !== '') {
                            _this.$parent.searchMap[item.field] = formatterVal
                        } else {
                            _this.$parent.searchMap[item.field] = searchText
                        }
                    })
                } else {
                    const _this = this
                    this.searchColumns.forEach(function(item) {
                        _this.advSearchMap[item.field] = ''
                        _this.$parent.searchMap[item.field] = ''
                    })
                }

                this.$parent.loadListdata()
            } else if (searchText === null) {
                if (this.advSearchStyle === 'dragpanel' && this.searchFormFieldInfo.length === 0) {
                    const format = this.$vnode.context.pageInfo.passenger
                    let copyTbColumns = JSON.parse(JSON.stringify(this.tbColumns))
                    copyTbColumns = sortByKey(copyTbColumns, 'listAdvSearchIndex', 'asc')
                    copyTbColumns.forEach(column => {
                        if (column.searchable === true) {
                            if (column.listAdvSearchElement === 'date') {
                                const formField_start = {
                                    'elementCanEdit': 1,
                                    'elementReadonly': 0,
                                    'isRequired': 0,
                                    'elementType': column.listAdvSearchElement,
                                    'emptyMessage': '请选择' + column.title + '(开始)',
                                    'formTdColspan': 8,
                                    'propComment': column.title + '(开始)',
                                    'propName': column.field + '_START',
                                    'propType': column.propType,
                                    'elementFormatter': column.propFormatter || column.elementFormatter,
                                    'searchabled': true

                                }

                                if ((column.elementFormatter && column.elementFormatter.indexOf('format：') !== -1) || (column.propFormatter && column.propFormatter.indexOf('format：') !== -1)) {
                                    formField_start.textFormatter = (column.propFormatter || column.elementFormatter).split('format：')[1].replace('\r\n', '').replace('\n', '')
                                } else {
                                    formField_start.textFormatter = 'yyyy-MM-dd HH:mm:ss'
                                }
                                if (formField_start.textFormatter.split(' ').length > 1) {
                                    formField_start.pickerType = 'datetime'
                                } else {
                                    formField_start.pickerType = 'date'
                                }
                                this.searchFormFieldInfo.push(formField_start)

                                const formField_end = {
                                    'elementCanEdit': 1,
                                    'elementReadonly': 0,
                                    'isRequired': 0,
                                    'elementType': column.listAdvSearchElement,
                                    'emptyMessage': '请选择' + column.title + '(结束)',
                                    'formTdColspan': 8,
                                    'propComment': column.title + '(结束)',
                                    'propName': column.field + '_END',
                                    'propType': column.propType,
                                    'elementFormatter': column.propFormatter || column.elementFormatter,
                                    'searchabled': true,
                                    'textFormatter': formField_start.textFormatter,
                                    'pickerType': formField_start.pickerType
                                }

                                this.searchFormFieldInfo.push(formField_end)
                            } else if (format !== undefined && format[column.field + 'Options'] && (column.listAdvSearchElement === 'select' || column.listAdvSearchElement === 'radio' || column.listAdvSearchElement === 'checkbox')) {
                                const formField_select = {
                                    'elementCanEdit': 1,
                                    'elementReadonly': 0,
                                    'isRequired': 0,
                                    'elementType': column.listAdvSearchElement,
                                    'emptyMessage': '请选择' + column.title,
                                    'formTdColspan': 8,
                                    'propComment': column.title,
                                    'propName': column.field,
                                    'propType': column.propType,
                                    'elementFormatter': column.propFormatter || column.elementFormatter,
                                    'searchabled': true,
                                    'valueMinLength': null,
                                    'formatterMap': format[column.field + 'Options']
                                }
                                this.searchFormFieldInfo.push(formField_select)
                            } else {
                                const formField = {
                                    'elementCanEdit': 1,
                                    'elementReadonly': 0,
                                    'isRequired': 0,
                                    'elementType': column.listAdvSearchElement || 'input',
                                    'emptyMessage': '请输入' + column.title,
                                    'formTdColspan': 8,
                                    'propComment': column.title,
                                    'propName': column.field,
                                    'propType': column.propType || 'String',
                                    'elementFormatter': column.propFormatter || column.elementFormatter,
                                    'searchabled': true,
                                    'valueMinLength': null
                                }

                                this.searchFormFieldInfo.push(formField)
                            }
                        }

                        if (this.advSearchMap[column.field] === undefined) {
                            this.advSearchMap[column.field] = null
                        }
                    })
                }

                this.dialogFormVisible = !this.dialogFormVisible
                this.$nextTick(() => {
                    if (this.dialogFormVisible) {
                        const scrollbar = document.querySelector('.app-main .el-scrollbar .el-scrollbar__wrap')
                        if (scrollbar) scrollbar.scrollTop = 0
                    }
                    const searchInput = document.querySelector('.navbar-search .el-input__inner')
                    if (searchInput !== null) { searchInput.disabled = this.dialogFormVisible }
                    this.$bus.emit('unfloadAdvSearch', this.dialogFormVisible)
                })
            }
        },
        resetDateSearchField() {
            const _this = this
            _this.searchColumns.forEach(column => {
                if (column.listAdvSearchElement === 'date') {
                    let start = _this.advSearchMap[column.field + '_START']
                    if (start && start !== '' && start !== null) {
                        start = start.replace('年', '/').replace('月', '/').replace('日', '').replace('时', ':').replace('分', ':').replace('秒', '').replace('-', '/')

                        _this.advSearchMap[column.field + '_START'] = new Date(start)

                        if (this.advSearchStyle === 'dragpanel') {
                            _this.advSearchMap[column.field + '_START'] = moment(_this.advSearchMap[column.field + '_START']).format('YYYY-MM-DD HH:mm:ss')
                        }
                    }
                    let end = _this.advSearchMap[column.field + '_END']
                    if (end && end !== '' && end !== null) {
                        end = end.replace('年', '/').replace('月', '/').replace('日', '').replace('时', ':').replace('分', ':').replace('秒', '').replace('-', '/')

                        _this.advSearchMap[column.field + '_END'] = new Date(end)

                        if (this.advSearchStyle === 'dragpanel') {
                            _this.advSearchMap[column.field + '_END'] = moment(_this.advSearchMap[column.field + '_END']).format('YYYY-MM-DD HH:mm:ss')
                        }
                    }
                }
            })
        },
        handleAdvSearch() {
            this.$bus.emit('clearSearchText')
            this.searchConditions = []
            const _this = this
            for (const name in _this.advSearchMap) {
                let val = _this.advSearchMap[name]
                if (val !== undefined && val !== null && val !== '' && name.substring(name.length - 1) !== '=') {
                    const column = _this.searchColumns.filter(item => {
                        if (item.field === name || item.field + '_START' === name || item.field + '_END' === name) return true
                    })[0]
                    if (column.formatterMap && column.formatterMap[val]) val = column.formatterMap[val]

                    const condition = { field: name, label: column.title, value: val }
                    if (column.listAdvSearchElement === 'date') {
                        if (_this.advSearchMap[column.field + '_START'] > _this.advSearchMap[column.field + '_END'] && _this.advSearchMap[column.field + '_END'] !== '') {
                            this.$message({ type: 'warning', message: (column.title + '开始时间必须在结束时间之前'), showClose: true })
                            return
                        }
                        if (name.indexOf('_START') !== -1) {
                            condition.label += '(开始)'
                        } else if (name.indexOf('_END') !== -1) {
                            condition.label += '(结束)'
                        }

                        if (typeof val === 'object') {
                            condition.value = moment(val).format(column.propFormatter.replace('yyyy', 'YYYY').replace('dd', 'DD').replace('format：', ''))

                            _this.advSearchMap[name] = condition.value
                        } else if (column.propFormatter.indexOf(' HH:mm') === -1) {
                            _this.advSearchMap[name] = condition.value.replace(' 00:00:00', '')
                        }
                        if (column.datePickerType === 'date' && condition.value !== null) {
                            condition.value = condition.value.split(' ')[0]
                        }
                    }

                    _this.searchConditions.push(condition)
                }
            }
            const searchobj = this.advSearchMap
            this.searchColumns.forEach(item => {
                if (item.listAdvSearchElement === 'date' && item.propType === 'java.util.Date') {
                    const reg = /[\u4e00-\u9fa5]/g
                    if (searchobj[item.field + '_START']) {
                        const time = searchobj[item.field + '_START'].split(' ')
                        let start = ''
                        if (time.length > 1) {
                            const date = searchobj[item.field + '_START'].split(' ')[0].replace(reg, '-')
                            const tim = searchobj[item.field + '_START'].split(' ')[1].replace(reg, ':')
                            start = date.substr(0, 10) + ' ' + tim.substr(0, 8)
                        } else {
                            start = searchobj[item.field + '_START'].split(' ')[0].replace(reg, '-')
                            start = start.substr(0, 10)
                        }
                        searchobj[item.field + '_START'] = time.length > 1 ? moment(new Date(start)).format('YYYY-MM-DD HH:mm') : moment(new Date(start)).format('YYYY-MM-DD')
                    }
                    if (searchobj[item.field + '_END']) {
                        const time = searchobj[item.field + '_END'].split(' ')
                        let end = ''
                        if (time.length > 1) {
                            const date = searchobj[item.field + '_END'].split(' ')[0].replace(reg, '-')
                            const tim = searchobj[item.field + '_END'].split(' ')[1].replace(reg, ':')
                            end = date.substr(0, 10) + ' ' + tim.substr(0, 8)
                        } else {
                            end = searchobj[item.field + '_END'].split(' ')[0].replace(reg, '-')
                            end = end.substr(0, 10)
                        }
                        searchobj[item.field + '_END'] = time.length > 1 ? moment(new Date(end)).format('YYYY-MM-DD HH:mm') : moment(new Date(end)).format('YYYY-MM-DD 23:59:59')
                    }
                }
                // else if (item.listAdvSearchElement === 'select') {
                //     debugger
                //     searchobj[item.field + '='] = searchobj[item.field]
                // }
            })

            if (this.advSearchStyle !== 'dragpanel') {
                this.dialogFormVisible = false
            }

            this.$parent.searchAndOr = 'and'
            this.$parent.searchMap = searchobj
            this.$parent.loadListdata()

            if (this.advSearchStyle === 'dragpanel') {
                this.resetDateSearchField()
            }
        },
        clearSearchCondition(condition) {
            if (typeof condition === 'undefined') {
                this.searchConditions = []
                for (var key in this.advSearchMap) {
                    this.$set(this.advSearchMap, key, null)
                }
                if (this.advSearchStyle === 'dragpanel') {
                    this.dialogFormVisible = false
                    this.$nextTick(() => {
                        this.dialogFormVisible = true
                    })
                }
            } else {
                delete this.advSearchMap[condition.field]
                for (let i = 0; i < this.searchConditions.length; i++) {
                    if (this.searchConditions[i].field === condition.field) {
                        this.searchConditions.splice(i, 1)
                        break
                    }
                }
            }

            this.$parent.searchAndOr = 'and'
            this.$parent.searchMap = this.advSearchMap
            this.$parent.loadListdata()
        }
    }
}
</script>

<style lang="scss" scoped>
 @import "~@/wapp/common/styles/variables.scss";

.search-condition-bar{
     margin-top:-10px;
    width: 100%;
    color: $dark;
    height: $menuItemHeight;
    line-height: $menuItemHeight;

    label {
        float: left;
        font-weight:400!important;
        font-size: 14px;
    }

    .scroll-pane-container{
        font-size: $contentFontSize;
        float: left;
        .scroll-container{
            width: calc(100vw - #{$sideBarWidth} - 180px - 17px);

            span{
                margin: 0 4px;
                padding: 5px;
                border-radius: 3px;
                border: #dfe6ec solid 1px;

                i {
                    cursor: pointer;
                    margin-left: 5px;
                    &:hover{
                        background-color: #ff0000;
                        color: #fff;
                    }
                }
            }
        }
    }

    .clear-condition-btn{
        float: right;
        .el-button{
            padding-right:0px;
        }
    }
}
.date_time_inner{
    .el-input__inner{padding-left:25px!important;}
    .el-input__prefix{left:0px;right: auto;}
}

.dragpanel-container{
    padding-bottom: 10px;
    margin-bottom: 10px;
    border:1px solid #DEE2E6;
    border-radius: 4px;
    /deep/ .el-table{
        border: none;
        border-radius: 0;
        &::after{display: none;}
        .el-table__body-wrapper{
            .el-table__body{
                tr td:last-child{
                    border-right: 0;
                }
            }
        }
    }
    .panel-footer{
        margin: 10px 10px 0;
        text-align: center;
    }
}
</style>

